package cn.msqweb.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.msqweb.entity.Category;
import cn.msqweb.ex.handler.ex.BusinessException;
import cn.msqweb.mapper.CategoryMapper;
import cn.msqweb.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Boolean saveCategory(Category category) {
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());
        return categoryMapper.insert(category)>0;
    }

    @Override
    public Boolean modifyCategory(Category category) {
        Long categoryId = category.getCategoryId();
        // 1 -> 1:
        // 2 -> 2:

        // 查询当前修改类目的详情
        Category oldCategory = categoryMapper.selectById(categoryId);

        // 1 -> 2:
        if (0 == oldCategory.getParentId() && null != category.getParentId() && 0 != category.getParentId()) {
            // 查询当前类目的子类目集合
            List<Category> child = categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                    .eq(Category::getParentId, categoryId)
            );
            if (CollectionUtil.isNotEmpty(child) && child.size() != 0) {
                // 说明当前类目包含子类目集合，不可修改
                throw new BusinessException("当前类目包含子类目集合，不可修改");
            }
        }
        // 2 -> 1:
        if (0!= oldCategory.getCategoryId() && null == category.getParentId()) {
            category.setParentId(0L);
        }

        category.setUpdateTime(new Date());
        return categoryMapper.updateById(category)>0;
    }

    @Override
    public Boolean removeCategoryById(Long categoryId) {
        // 查询类目的子类目集合
        List<Category> child = categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId, categoryId)
        );
        if (CollectionUtil.isNotEmpty(child) && child.size() != 0) {
            throw new BusinessException("类目包含子类目，不可删除");
        }
        return categoryMapper.deleteById(categoryId)>0;
    }
}
